
#include "Main.h"

#include "AudioHelper.h"

float AudioHelper::s_afLeftSamples[uNUM_OSC_SAMPLES];
float AudioHelper::s_afRightSamples[uNUM_OSC_SAMPLES];

void AudioHelper::Initialise()
{
	FridgeLog("AudioHelper init\n");

	memset( s_afLeftSamples, 0, sizeof( float ) * uNUM_OSC_SAMPLES );
	memset( s_afRightSamples, 0, sizeof( float ) * uNUM_OSC_SAMPLES );
	
	Platform_Initialise();
}

void AudioHelper::Update()
{
	Platform_Update(); 
}

void AudioHelper::Shutdown()
{
	Platform_Shutdown();
}

float AudioHelper::GetOsc( float fTime, float fWidth, FRIDGE_AUDIO_CHANNEL eChannel )
{
	const u_int uFirstSample = fTime <= 0.0f ? 0 : static_cast< u_int >( fTime * ( uNUM_OSC_SAMPLES - 1 ) );
	const u_int uNumSamples = fWidth <= 0.0f ? 0 : static_cast< u_int >( fWidth * ( uNUM_OSC_SAMPLES - 1 ) );
	const u_int uLastSample = MACRO_MIN( uNUM_OSC_SAMPLES - 1, uFirstSample + uNumSamples );

	float fPeakSample = 0.0f;
	for( u_int uSample = uFirstSample; uSample <= uLastSample; ++uSample )
	{
		float fCurrentSample = 0.0f;
		switch( eChannel )
		{
			case CHANNEL_LEFT:  fCurrentSample = s_afLeftSamples[ uSample ]; break;
			case CHANNEL_RIGHT: fCurrentSample = s_afLeftSamples[ uSample ]; break;

			case CHANNEL_MONO:
			{
				fCurrentSample = fabs( s_afLeftSamples[ uSample ] ) > fabs( s_afRightSamples[ uSample ] ) ? s_afLeftSamples[ uSample ] : s_afRightSamples[ uSample ];
			}
			break;
		}

		fPeakSample = fabs( fCurrentSample ) > fabs( fPeakSample ) ? fCurrentSample : fPeakSample;
	}

	return fPeakSample;
}

// eof
